package com.mflex.mwms.activity;

import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;

import com.mflex.mwms.R;
import com.mflex.mwms.adapter.TransferOffAdapter;
import com.mflex.mwms.manager.TokenManager;
import com.mflex.mwms.model.CustomApiResult;
import com.mflex.mwms.model.SendTransferTaskRequest;
import com.mflex.mwms.model.Task;
import com.mflex.mwms.model.TaskDetail;
import com.mflex.mwms.model.TransferDetail;
import com.mflex.mwms.model.TransferDetailTaskRequest;
import com.mflex.mwms.model.TransferTaskRequest;
import com.mflex.mwms.utils.MMKVUtils;
import com.mflex.mwms.utils.MessageUtils;
import com.mflex.mwms.utils.XToastUtils;
import com.xuexiang.xhttp2.XHttp;
import com.xuexiang.xhttp2.callback.CallBackProxy;
import com.xuexiang.xhttp2.callback.SimpleCallBack;
import com.xuexiang.xhttp2.exception.ApiException;
import com.xuexiang.xui.utils.CollectionUtils;
import com.xuexiang.xui.utils.WidgetUtils;
import com.xuexiang.xui.widget.dialog.MiniLoadingDialog;
import com.xuexiang.xui.widget.picker.widget.OptionsPickerView;
import com.xuexiang.xui.widget.picker.widget.builder.OptionsPickerBuilder;
import com.xuexiang.xui.widget.picker.widget.listener.OnOptionsSelectListener;
import com.xuexiang.xutil.common.StringUtils;
import com.xuexiang.xutil.net.JsonUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 调拨出库
 */
public class TransferOffActivity extends BaseActivity {
    @BindView(R.id.stv_FromWH)
    EditText stvFromWH;

    @BindView(R.id.stv_ToWH)
    EditText stvToWH;

    @BindView(R.id.stv_Pallet)
    EditText stvPallet;

    @BindView(R.id.stv_BoxNumber)
    EditText stvBoxNumber;

    @BindView(R.id.stv_TaskNo)
    EditText stvTaskNo;

    @BindView(R.id.stv_BoxQty)
    EditText stvBoxQty;

    @BindView(R.id.lvBoxList)
    ListView lvBoxList;

    @BindView(R.id.button_clear)
    Button buttonClear;

    @BindView(R.id.button_save)
    Button buttonSave;

    MiniLoadingDialog mMiniLoadingDialog;

    String taskNo;
    List<TaskDetail> taskDetailist;

    private String[] localtionOption;
    private int localtionSelectOption = 0;

    private int boxQty = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_transfer_off);
        ButterKnife.bind(this);
        mMiniLoadingDialog = WidgetUtils.getMiniLoadingDialog(this, "加载...");

        taskDetailist = new ArrayList<>();
        taskNo = "";
        TransferOffAdapter transferOnAdapter = new TransferOffAdapter(this, taskDetailist);
        lvBoxList.setAdapter(transferOnAdapter);

        stvTaskNo.setFocusable(false);
        stvFromWH.setFocusable(false);
        stvFromWH.setText(MMKVUtils.getString("Warehose", ""));
        stvToWH.setFocusable(false);
        stvToWH.setOnClickListener(this);
        buttonClear.setOnClickListener(this);
        buttonSave.setOnClickListener(this);
//        buttonRemove.setOnClickListener(this);

        stvPallet.setOnKeyListener(this);
        stvBoxNumber.setOnKeyListener(this);
        initData();
    }

    @Override
    public boolean onKey(View view, int i, KeyEvent keyEvent) {
        if (keyEvent.getAction() == KeyEvent.ACTION_DOWN && (i == 66 || i == 61)) {
            switch (view.getId()) {
                case R.id.stv_Pallet:
                    checkPallet(view);
                    break;
                case R.id.stv_BoxNumber:
                    checkBoxNumber(view);
                    break;
                default:
                    break;
            }
        }
        return false;
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.button_clear:
                clearButtonMd(view);
                break;
            case R.id.button_save:
                saveButtonMd(view);
                break;
            case R.id.stv_ToWH:
                showLocaltionPickerView();
                break;
            default:
                break;
        }
    }

    private void clearButtonMd(View v) {
        stvBoxNumber.setText("");
        stvPallet.setText("");
        stvToWH.setText("");
        stvTaskNo.setText("");
        stvBoxQty.setText("");

        taskDetailist = new ArrayList<>();
        taskNo = "";
        boxQty = 0;
        TransferOffAdapter transferOnAdapter = new TransferOffAdapter(this, taskDetailist);
        lvBoxList.setAdapter(transferOnAdapter);
        XToastUtils.success("重置成功！");
    }

    private void saveButtonMd(View v) {
        if (StringUtils.isEmpty(stvTaskNo.getText().toString())) {
//            XToastUtils.error("任务号未获取");
            MessageUtils.errorMsgAndVoice(TransferOffActivity.this, "任务号未获取");
            return;
        }

        if (StringUtils.isEmpty(stvToWH.getText().toString())) {
//            XToastUtils.error("调入仓库未选择");
            MessageUtils.errorMsgAndVoice(TransferOffActivity.this, "调入仓库未选择");
            return;
        }

        if (StringUtils.isEmpty(stvTaskNo.getText().toString())) {
//            XToastUtils.error("任务号未获取");
            MessageUtils.errorMsgAndVoice(TransferOffActivity.this, "任务号未获取");
            return;
        }

        SendTransferTaskRequest request = new SendTransferTaskRequest();
        request.setTaskNo(stvTaskNo.getText().toString());
        mMiniLoadingDialog.show();
        XHttp.post("api/Task/SendTransferTask")
                .upJson(JsonUtil.toJson(request))
                .syncRequest(false)
                .onMainThread(true)
                .accessToken(true)
                .timeOut(120000)
                .execute(new CallBackProxy<CustomApiResult<String>, String>(new SimpleCallBack<String>() {

                    @Override
                    public void onSuccess(String response) {
                        mMiniLoadingDialog.dismiss();

                        XToastUtils.success("发送成功！");

                        stvBoxNumber.setText("");
                        stvPallet.setText("");
                        stvToWH.setText("");
                        stvTaskNo.setText("");

                        taskDetailist = new ArrayList<>();
                        taskNo = "";
                        TransferOffAdapter transferOnAdapter = new TransferOffAdapter(TransferOffActivity.this, taskDetailist);
                        lvBoxList.setAdapter(transferOnAdapter);
                    }

                    @Override
                    public void onError(ApiException e) {
                        mMiniLoadingDialog.dismiss();
                        stvPallet.setText("");
                        stvPallet.requestFocus();
//                        if (e.getCode() == 100) {
//                            new MaterialDialog.Builder(v.getContext())
//                                    .iconRes(R.drawable.icon_warning)
//                                    .title(R.string.tip_warning)
//                                    .content(e.getMessage())
//                                    .positiveText(R.string.lab_submit)
//                                    .show();
//                        }
//                        if (e.getCode() == 200) {
//                            new MaterialDialog.Builder(v.getContext())
//                                    .iconRes(R.drawable.icon_tip)
//                                    .title(R.string.tip_infos)
//                                    .content(e.getMessage())
//                                    .positiveText(R.string.lab_submit)
//                                    .show();
//                        }
                        MessageUtils.errorMsgAndVoice(TransferOffActivity.this, e);
                    }
                }) {
                });
    }

    private void checkPallet(View v) {
        if (StringUtils.isEmpty(stvToWH.getText().toString())) {
//            XToastUtils.error("调入仓库未选择");
            MessageUtils.errorMsgAndVoice(TransferOffActivity.this, "调入仓库未选择");
            return;
        }

        TransferTaskRequest transferTaskRequest = new TransferTaskRequest();
        transferTaskRequest.setFromWH(stvFromWH.getText().toString());
        transferTaskRequest.setToWH(stvToWH.getText().toString());
        transferTaskRequest.setPallet(stvPallet.getText().toString());
        mMiniLoadingDialog.show();
        XHttp.post("api/Task/TransferTask")
                .upJson(JsonUtil.toJson(transferTaskRequest))
                .syncRequest(false)
                .onMainThread(true)
                .accessToken(true)
                .timeOut(120000)
                .execute(new CallBackProxy<CustomApiResult<List<Task>>, List<Task>>(new SimpleCallBack<List<Task>>() {

                    @Override
                    public void onSuccess(List<Task> response) {

                        if (!StringUtils.equals(stvToWH.getText().toString(), response.get(0).getToWH())) {
//                            XToastUtils.warning("任务已存在，调入仓库不一致，已调整", 3000);
                            MessageUtils.errorMsgAndVoice(TransferOffActivity.this, "任务已存在，调入仓库不一致，已调整");
                            stvToWH.setText(response.get(0).getToWH());
                        }

                        mMiniLoadingDialog.dismiss();

                        taskDetailist = response.get(0).getTaskDetails();

                        taskNo = response.get(0).getTaskNo();

                        TransferOffAdapter transferOffAdapter = new TransferOffAdapter(TransferOffActivity.this, response.get(0).getTaskDetails());
                        lvBoxList.setAdapter(transferOffAdapter);

                        stvTaskNo.setText(response.get(0).getTaskNo());
                    }

                    @Override
                    public void onError(ApiException e) {
                        mMiniLoadingDialog.dismiss();
                        stvPallet.setText("");
                        stvPallet.requestFocus();
//                        if (e.getCode() == 100) {
//                            new MaterialDialog.Builder(v.getContext())
//                                    .iconRes(R.drawable.icon_warning)
//                                    .title(R.string.tip_warning)
//                                    .content(e.getMessage())
//                                    .positiveText(R.string.lab_submit)
//                                    .show();
//                        }
//                        if (e.getCode() == 200) {
//                            new MaterialDialog.Builder(v.getContext())
//                                    .iconRes(R.drawable.icon_tip)
//                                    .title(R.string.tip_infos)
//                                    .content(e.getMessage())
//                                    .positiveText(R.string.lab_submit)
//                                    .show();
//                        }
                        MessageUtils.errorMsgAndVoice(TransferOffActivity.this, e);
                    }
                }) {
                });
    }

    private void checkBoxNumber(View v) {
        if (StringUtils.isEmpty(stvPallet.getText().toString())) {
//            XToastUtils.error("栈板未输入");
            MessageUtils.errorMsgAndVoice(TransferOffActivity.this, "栈板未输入");
            return;
        }

        TransferDetailTaskRequest transferDetailTaskRequest = new TransferDetailTaskRequest();

        List<TransferDetail> transferDetailList = new ArrayList<>();

        TransferDetail transferDetail = new TransferDetail();
        transferDetail.setBoxNumber(stvBoxNumber.getText().toString());
        transferDetail.setAciton(0);
        transferDetailList.add(transferDetail);

        transferDetailTaskRequest.setTaskNo(stvTaskNo.getText().toString());
        transferDetailTaskRequest.setDetails(transferDetailList);

        mMiniLoadingDialog.show();
        XHttp.post("api/Task/TransferDetailTask")
                .upJson(JsonUtil.toJson(transferDetailTaskRequest))
                .syncRequest(false)
                .onMainThread(true)
                .accessToken(true)
                .timeOut(120000)
                .execute(new CallBackProxy<CustomApiResult<List<Task>>, List<Task>>(new SimpleCallBack<List<Task>>() {

                    @Override
                    public void onSuccess(List<Task> response) {
                        mMiniLoadingDialog.dismiss();
                        stvBoxNumber.setText("");
                        stvBoxNumber.requestFocus();

                        boxQty=boxQty+1;
                        stvBoxQty.setText(String.valueOf(boxQty));

                        TransferOffAdapter transferOffAdapter = new TransferOffAdapter(TransferOffActivity.this, response.get(0).getTaskDetails());
                        lvBoxList.setAdapter(transferOffAdapter);
                    }

                    @Override
                    public void onError(ApiException e) {
                        mMiniLoadingDialog.dismiss();
                        stvBoxNumber.setText("");
                        stvBoxNumber.requestFocus();
//                        if (e.getCode() == 100) {
//                            new MaterialDialog.Builder(v.getContext())
//                                    .iconRes(R.drawable.icon_warning)
//                                    .title(R.string.tip_warning)
//                                    .content(e.getMessage())
//                                    .positiveText(R.string.lab_submit)
//                                    .show();
//                        }
//                        if (e.getCode() == 200) {
//                            new MaterialDialog.Builder(v.getContext())
//                                    .iconRes(R.drawable.icon_tip)
//                                    .title(R.string.tip_infos)
//                                    .content(e.getMessage())
//                                    .positiveText(R.string.lab_submit)
//                                    .show();
//                        }
                        MessageUtils.errorMsgAndVoice(TransferOffActivity.this, e);
                    }
                }) {
                });
    }

    private void removeButtonMd(View v) {
        TransferDetailTaskRequest transferDetailTaskRequest = new TransferDetailTaskRequest();
        List<TransferDetail> transferDetailList = new ArrayList<>();
        for (TaskDetail detail : taskDetailist) {
            if (detail.checked) {
                TransferDetail transferDetail = new TransferDetail();
                transferDetail.setBoxNumber(detail.getDetailName());
                transferDetail.setAciton(1);
                transferDetailList.add(transferDetail);
            }
        }
        transferDetailTaskRequest.setDetails(transferDetailList);
        transferDetailTaskRequest.setTaskNo(stvTaskNo.getText().toString());

        if (CollectionUtils.isEmpty(transferDetailList)) {
//            new MaterialDialog.Builder(v.getContext())
//                    .iconRes(R.drawable.icon_warning)
//                    .title(R.string.tip_warning)
//                    .content("没有选择删除数据")
//                    .positiveText(R.string.lab_submit)
//                    .show();
            MessageUtils.errorMsgAndVoice(TransferOffActivity.this, "没有选择删除数据");
            return;
        }

        transferDetailTaskRequest.setTaskNo(stvFromWH.getText().toString());
        transferDetailTaskRequest.setDetails(transferDetailList);

        mMiniLoadingDialog.show();
        XHttp.post("api/Task/TransferDetailTask")
                .upJson(JsonUtil.toJson(transferDetailTaskRequest))
                .syncRequest(false)
                .onMainThread(true)
                .accessToken(true)
                .timeOut(120000)
                .execute(new CallBackProxy<CustomApiResult<Task>, Task>(new SimpleCallBack<Task>() {

                    @Override
                    public void onSuccess(Task response) {
                        mMiniLoadingDialog.dismiss();
                        XToastUtils.success("删除成功", 2500);
                    }

                    @Override
                    public void onError(ApiException e) {
                        mMiniLoadingDialog.dismiss();
                        stvPallet.setText("");
                        stvPallet.requestFocus();
//                        if (e.getCode() == 100) {
//                            new MaterialDialog.Builder(v.getContext())
//                                    .iconRes(R.drawable.icon_warning)
//                                    .title(R.string.tip_warning)
//                                    .content(e.getMessage())
//                                    .positiveText(R.string.lab_submit)
//                                    .show();
//                        }
//                        if (e.getCode() == 200) {
//                            new MaterialDialog.Builder(v.getContext())
//                                    .iconRes(R.drawable.icon_tip)
//                                    .title(R.string.tip_infos)
//                                    .content(e.getMessage())
//                                    .positiveText(R.string.lab_submit)
//                                    .show();
//                        }
                        MessageUtils.errorMsgAndVoice(TransferOffActivity.this, e);
                    }
                }) {
                });
    }

    private void initData() {
        mMiniLoadingDialog.show();
        XHttp.get("api/User/GetUserWarehouse")
                .params("userName", TokenManager.getInstance().getLoginUser().getUserName())
                .syncRequest(false)
                .onMainThread(true)
                .accessToken(true)
                .timeOut(120000)
                .execute(new CallBackProxy<CustomApiResult<List<String>>, List<String>>(new SimpleCallBack<List<String>>() {
                    @Override
                    public void onSuccess(List<String> response) {
                        mMiniLoadingDialog.dismiss();
                        localtionOption = new String[response.size()];
                        response.toArray(localtionOption);
                    }

                    @Override
                    public void onError(ApiException e) {
                        mMiniLoadingDialog.dismiss();
//                        if (e.getCode() == 100) {
//                            new MaterialDialog.Builder(TransferOffActivity.this)
//                                    .iconRes(R.drawable.icon_warning)
//                                    .title(R.string.tip_warning)
//                                    .content(e.getMessage())
//                                    .positiveText(R.string.lab_submit)
//                                    .show();
//                        }
//                        if (e.getCode() == 200) {
//                            new MaterialDialog.Builder(TransferOffActivity.this)
//                                    .iconRes(R.drawable.icon_tip)
//                                    .title(R.string.tip_infos)
//                                    .content(e.getMessage())
//                                    .positiveText(R.string.lab_submit)
//                                    .show();
//                        }
                        MessageUtils.errorMsgAndVoice(TransferOffActivity.this, e);
                    }
                }) {
                });
    }

    private void showLocaltionPickerView() {
        OptionsPickerView pvOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public boolean onOptionsSelect(View v, int options1, int options2, int options3) {
                localtionSelectOption = options1;
                stvToWH.setText(localtionOption[localtionSelectOption]);
                return false;
            }
        })
                .setTitleText("调入仓库")
                .setSelectOptions(localtionSelectOption)
                .build();
        pvOptions.setPicker(localtionOption);
        pvOptions.show();
    }
}